package com.rgp.servicedriveruser.service.impl;

import com.rgp.internalcommon.common.CommonStatusEnum;
import com.rgp.internalcommon.dto.ResponseResult;
import com.rgp.internalcommon.response.TerminalResponse;
import com.rgp.internalcommon.response.TrackResponse;
import com.rgp.servicedriveruser.feign.ServiceMapClient;
import com.rgp.servicedriveruser.mapper.CarMapper;
import com.rgp.servicedriveruser.pojo.Car;
import com.rgp.servicedriveruser.service.CarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author nhp
 * @version 1.0
 * @description TODO
 * @date 2024-04-16 20:08
 */
@Service
public class CarServiceImpl implements CarService {

    @Autowired
    private CarMapper carMapper;

    @Autowired
    private ServiceMapClient serviceMapClient;

    @Override
    public ResponseResult selectCarById(Long id) {
        Car car = carMapper.selectById(id);
        if (car != null){
            return ResponseResult.success(car);
        }else{
            return ResponseResult.fail(CommonStatusEnum.CAR_NOT_EXIST_ERROR);
        }

    }

    @Override
    public ResponseResult insertCarEntity(Car car) {

        // 改造插入车辆信息的代码
        //1.先将车辆信息插入到db，获得此条车辆数据的id
        int result = carMapper.insert(car);
        if (result != 1) {
            return ResponseResult.fail(CommonStatusEnum.CAR_INSERT_ERROR);
        }
        //获得车辆信息的id 与 车牌号
        Long id = car.getId();
        String vehicleNo = car.getVehicleNo();
        //2.根据车牌号生成车辆对应的终端id
        ResponseResult<TerminalResponse> responseResult = serviceMapClient.addTerminal(vehicleNo,id);
        Long tid = responseResult.getData().getTid();
        //终端id：tid
        car.setTid(tid);
        //3.根据车辆对应的终端tid，生成对应轨迹trid
        ResponseResult<TrackResponse> track = serviceMapClient.addTrack(tid);
        //轨迹id：trid
        Integer trid = track.getData().getTrid();
        //轨迹名称：trname
        String trname = track.getData().getTrname();
        car.setTrid(trid);
        car.setTrName(trname);
        //4.对当前车辆的数据进行更新，目的是将当前车辆对应的终端id[tid]、轨迹id[trid]、轨迹名称[trname]设置到db中
        int updateById = carMapper.updateById(car);
        if (updateById != 1){
            return ResponseResult.fail(CommonStatusEnum.CAR_UPDATE_ERROR);
        }
        return ResponseResult.success();
    }
}